﻿using System.Collections.Generic;
using System.Linq;
using DesignPatterns.BuilderPattern.Models;

namespace DesignPatterns.BuilderPattern.Repositories
{
    public interface IPhoneNumberRepository 
    {
        List<PhoneNumber> GetAll();
        PhoneNumber GetById(int id);
    }

    public class PhoneNumberRepository : IPersonBuilder, IPhoneNumberRepository
    {
        public List<PhoneNumber> GetAll()
        {
            return new List<PhoneNumber>
            {
                new PhoneNumber { Id = 1, AreaCode = 717, Number = "235-5105"},
                new PhoneNumber { Id = 2, AreaCode = 502, Number = "123-4568"},
                new PhoneNumber { Id = 3, AreaCode = 717, Number = "987-6543"},
                new PhoneNumber { Id = 4, AreaCode = 125, Number = "457-6547"},
                new PhoneNumber { Id = 5, AreaCode = 555, Number = "852-9638"},
                new PhoneNumber { Id = 6, AreaCode = 812, Number = "197-3486"}
            };
        }

        public PhoneNumber GetById(int id)
        {
            return GetAll().FirstOrDefault(i => i.Id == id);
        }

        public List<PhoneNumber> GetByPerson(int personId)
        {
            /****** THIS METHOD WOULD BE EASY TO UNIT/INTEGRATION TEST ******/

            //Query the database to get address for this person id
            //this would probably be a many to many table
            return GetAll().Where(i => new[] {2, 5, 6}.Contains(i.Id)).ToList();
        }

        public void SaveForPerson(int personId, List<PhoneNumber> numbers)
        {
            /****** THIS METHOD WOULD BE EASY TO UNIT/INTEGRATION TEST ******/

            //Save the many to many relations to the database
        }


        public void Populate(ref Person item)
        {
            if (item == null) return;

            item.PhoneNumbers = GetByPerson(item.Id);
        }

        public void Save(ref Person item)
        {
            if (item == null) return;
            
            SaveForPerson(item.Id, item.PhoneNumbers);
        }
    }
}
